package org.jwt.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author zqx
 * @date 2021-11-08
 */
@WebFilter("/api/*")
public class CorsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("允许跨域操作..");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse resp = (HttpServletResponse) servletResponse ;
        // 允许所有的域名
        resp.setHeader("Access-Control-Allow-Origin", "*");

        // 允许请求所有的方法
        resp.setHeader("Access-Control-Allow-Methods", "*");

        // 允许请求头信息字段（Authorization）
        resp.setHeader("Access-Control-Allow-Headers", "Authorization,Origin,X-Requested-With,Content-Type,Accept,"
                + "content-Type,origin,x-requested-with,content-type,accept,authorization,token,id,X-Custom-Header,X-Cookie,Connection,User-Agent,Cookie,*");


        filterChain.doFilter(servletRequest,resp);
    }

    @Override
    public void destroy() {

    }
}
